// 修改账号的业务组件
import React, { useEffect, useState } from 'react'
import { Input, Modal } from '@kedacom/react-next'
import { checkAccount } from '@/utils/rules'
import { AccountViewProps } from './interface'
import { StyledAccount } from './style'
const useHook = (
	value: React.SetStateAction<string> | undefined,
	onConfirm: Function | undefined,
	onChange: Function | undefined,
	onIsRead: Function | undefined
) => {
	/**
	 * isRead:是否是自读页面
	 */
	const [isRead, setIsRead] = useState<boolean>(true)
	/**
	 * accountValue:账号
	 */
	const [accountValue, setAccountValue] = useState<string>('')
	useEffect(() => {
		setAccountValue(value ? value : '')
	}, [value])
	useEffect(() => {
		onIsRead && onIsRead(isRead)
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isRead])
	/**
	 * 编辑按钮
	 */
	const onHandleEdit = () => {
		var m = Modal.confirm({
			title: '提示',
			okText: '修改账号',
			onOk: () => {
				setIsRead(false)
				m.hide()
			},
			onCancel: () => {
				m.hide()
			},
			content: (
				<div>
					账号修改后，请牢记新账号！
					<br />
					账号丢失后无法找回，需返厂进行初始化。
				</div>
			),
		})
	}
	/**
	 * 点击确认按钮
	 */
	const onHandleConfirm = () => {
		if (accountValue) {
			if (checkAccount(accountValue)) {
				setIsRead(true)
				onConfirm && onConfirm(accountValue)
			}
		}
	}
	/**
	 * 点击清空内容
	 */
	const onHandleClear = () => {
		setAccountValue('')
	}

	/**
	 * 输入内容时
	 * @param v 输入的值
	 */
	const onAccountChange = (v: React.SetStateAction<string>) => {
		setAccountValue(v)
		onChange && onChange(v)
	}
	return {
		/**是否是自读页面 */
		isRead,
		/**输入框的值 */
		accountValue,
		/**输入框内容改变时 */
		onAccountChange,
		/**点击编辑图标 */
		onHandleEdit,
		/**点击确认图标 */
		onHandleConfirm,
		/**点击清空按钮 */
		onHandleClear,
	}
}
const AccountView = ({
	value,
	labelWidth = 130,
	inputWidth = 300,
	onConfirm,
	onChange,
	onIsRead,
}: AccountViewProps) => {
	const { isRead, ..._useHook } = useHook(value, onConfirm, onChange, onIsRead)
	return (
		<StyledAccount className="account-wrap" labelWidth={labelWidth}>
			<span className="label">账号</span>
			{isRead ? (
				<>
					<span className="read-account-text">{_useHook.accountValue}</span>
					<span className="icon edit-icon" onClick={_useHook.onHandleEdit}></span>
				</>
			) : (
				<>
					<div className="input-wrap">
						<Input
							width={inputWidth}
							placeholder="请输入账号"
							value={_useHook.accountValue}
							onChange={(e, value) => {
								_useHook.onAccountChange(value)
							}}
						/>
						<span className="require-icon"></span>
						<span className="account-warn">账号修改后，需使用新账号重新登录，请牢记新账号！</span>
					</div>
					<span className="icon confirm-icon" onClick={_useHook.onHandleConfirm}></span>
					<span className="icon cancel-icon" onClick={_useHook.onHandleClear}></span>
				</>
			)}
		</StyledAccount>
	)
}
export default AccountView
